import { App } from 'antd';
import { t } from 'i18next';
import { useMemo, useState } from 'react';

import pluginService from '@/api/services/pluginService';
import workbenchService from '@/api/services/workbenchService';
import { Alert, Empty, Search, Segmented } from '@/components/eai-design';
import { CircleLoading } from '@/components/loading';
import PagesHeader from '@/components/pages-header';
import TipDesc from '@/components/tipDesc/tipDesc';
import { useConfirm } from '@/hooks/use-confirm';
import { useScrollPagination } from '@/hooks/use-pagination/useVirtualScrollPagination';
import { useRouter } from '@/router/hooks';
import { useUserInfo } from '@/store/userStore';
import { PluginItem } from '@/types/plugin/type';
import { localPluginModules } from '@/types/workflow/template/constants';

import ToolsItem from '../components/tools-item/ToolsItem';

const messagePlugin =
  '系统预置多个官方插件，可用于快速搭建常见工作流场景，帮助高效部署。同时，支持自定义工作流的输入与输出参数，适用于封装具备通用性和可复用性的流程逻辑。';

const PluginCenter = () => {
  const router = useRouter();
  const [searchValue, setSearchValue] = useState<string>('');
  const { message } = App.useApp();
  const [refreshKey, setRefreshKey] = useState<number>(0);
  const { _id: userId } = useUserInfo();

  const [segmentedOptions, _] = useState<{ label: string; value: string }[]>([
    {
      label: '全部来源',
      value: 'all',
    },
    {
      label: '我创建的',
      value: 'self',
    },
  ]);
  const [activeSegmented, setActiveSegmented] = useState<string>('all');

  const {
    data: pluginList,
    isLoading: loading,
    ScrollData,
    setData,
  } = useScrollPagination(pluginService.getPluginList, {
    pageSize: 20,
    showLoadText: false,
    params: {
      searchText: searchValue,
      source: activeSegmented === 'all' ? undefined : 'self',
    },
    refreshDeps: [activeSegmented, searchValue, refreshKey],
  });

  const { openConfirm: openConfirmDel, ConfirmModal: ConfirmDelModal } = useConfirm({
    content: t('confirm_del_app_tip', { name: '插件' }),
    type: 'delete',
    hideFooter: false,
    showClose: false,
    showCancel: true,
  });

  const handleEditClick = (item: PluginItem) => {
    router.push(
      `/app/workflow?appId=${item.app_id}&shareId=${item.share_id}&from=/worklayouts/tools/pluginCenter`,
    );
  };

  const confirmDelete = async (appId: string) => {
    await workbenchService.deleteWorkDataApi(appId);
    message.success('删除成功');
    setRefreshKey((prev) => prev + 1);
  };

  const handleDeleteClick = async (item: PluginItem) => {
    const res = await pluginService.getPluginUsedCount(item.app_id);

    const confirm = () => {
      confirmDelete(item.app_id);
    };
    const { count } = res;
    if (count > 0) {
      openConfirmDel(confirm, undefined, t('confirm_del_plugin_inuse_tip', { count }))();
    } else {
      openConfirmDel(confirm, undefined, t('confirm_del_plugin_tip', { name: item.app_name }))();
    }
  };

  const pluginCount = useMemo(() => {
    const localPluginCount =
      activeSegmented === 'all'
        ? localPluginModules.filter((item) => item.name.includes(searchValue)).length
        : 0;
    const pluginCount = pluginList.length;
    return localPluginCount + pluginCount;
  }, [activeSegmented, pluginList.length, searchValue]);

  const getStatusText = (status: string) => {
    switch (status) {
      case 'reject':
        return '驳回';
      case 'pending':
        return '待审核';
      case 'pass':
        return '发布';
      default:
        return '未发布';
    }
  };

  const getStatusClass = (status: string) => {
    switch (status) {
      case 'reject':
        return 'bg-functional-red text-error';
      case 'pending':
        return 'bg-functional-orange text-warning';
      case 'pass':
        return 'bg-functional-green text-primary';
      default:
        return 'bg-functional-gray text-grays';
    }
  };

  return (
    <div className="flex h-full w-full flex-col rounded-default ">
      <PagesHeader>
        {t('sys.menu.pluginCenter')}
        <TipDesc title="用于管理已发布的智能体插件或者第三方插件" />
      </PagesHeader>
      <div className="relative mt-4 flex flex-1 flex-col px-5">
        <Alert message={messagePlugin} type="info" />
        <div className="mt-4 flex items-center gap-3">
          <Segmented
            value={activeSegmented}
            options={segmentedOptions}
            onChange={(value) => {
              setSearchValue('');
              setData([]);
              setActiveSegmented(value as string);
            }}
          />
          {activeSegmented === 'all' && (
            <div className="w-[240px]">
              <Search
                placeholder="搜索"
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
              />
            </div>
          )}
          {activeSegmented === 'self' && (
            <div className="w-[240px]">
              <Search
                placeholder="搜索"
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
              />
            </div>
          )}
        </div>
        {pluginCount > 0 && (
          <ScrollData className="h-[calc(100vh-190px)] overflow-y-auto overflow-x-hidden">
            {' '}
            <div className="mt-4 grid grid-cols-1 gap-4 pr-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
              {activeSegmented === 'all' &&
                localPluginModules
                  .filter((item) => item.name.includes(searchValue))
                  .map((item) => (
                    <ToolsItem
                      key={item.id}
                      name={item.name ?? ''}
                      description={item.intro ?? ''}
                      icon={item.avatar ? `${item.avatar}.svg` : ''}
                      author="官方插件"
                      isMine={false}
                      onEdit={() => {}}
                      onDelete={() => {}}
                    />
                  ))}
              {pluginList.length > 0 &&
                pluginList.map((item) => (
                  <ToolsItem
                    key={item.app_id}
                    name={item.app_name}
                    description={
                      item.review_status === 'reject'
                        ? `驳回原因：\n${item.review_description}`
                        : item.app_description
                    }
                    icon={item.app_logo}
                    author={
                      item.createUserId === userId ? '我' : `${item.group_name} / ${item.user_name}`
                    }
                    isMine={item.createUserId === userId}
                    status={
                      <div className="absolute right-[1px] top-[1px]">
                        {item.app_workbench_type === 'manager' && (
                          <div
                            className={`${getStatusClass(
                              item.review_status,
                            )} ml-2 h-[22px] rounded-bl-2xl rounded-tr-[10px] px-3 pt-[2px]  text-center text-xs font-medium  text-[white]`}
                          >
                            {getStatusText(item.review_status)}
                          </div>
                        )}
                      </div>
                    }
                    onEdit={() => handleEditClick(item)}
                    onDelete={() => handleDeleteClick(item)}
                  />
                ))}
            </div>
          </ScrollData>
        )}
        {pluginCount === 0 && (
          <div className="h-full text-center">
            <Empty fontText="暂无插件" />
          </div>
        )}
        {loading && (
          <div className="absolute inset-0 flex items-center justify-center">
            <CircleLoading />
          </div>
        )}
      </div>
      <ConfirmDelModal />
    </div>
  );
};

export default PluginCenter;
